const
	fs = require('fs'),
	shellHandler = require('./shell'),
	targetHandler = require('./target'),
	webshellHandler = require('./webshell'),
	flagHandler = require('./flag'),
	setHandler = require('./set'),
	uploadHandler = require('./upload'),
	cronHandler = require('./cron'),
	runHandler = require('./run');

let handler = {
	'namespace': function(self){console.log(self.namespace)},
	'help': require('./help'),
	'target': targetHandler,
	'webshell': webshellHandler,
	'flag': flagHandler,
	'set': setHandler,
	'upload': uploadHandler,
	'run': runHandler,
	'cron': cronHandler,
	// shell
	'ls': shellHandler('ls'),
	'pwd': shellHandler('pwd'),
	'cat': shellHandler('cat')
}

// alias & extends
handler.ns = handler.namespace;
handler.ws = handler.webshell;
handler.ip = handler.target;

handler.batrun = async (self) => {
	for(let target of self.namespace.targets){
		if (target.state === false) continue;
		for(let ws of self.namespace.webshells){
			try {
				await runHandler(self, target.id, ws.id);
				break;
			} catch(err) {
				console.error(err);
			}
		}
	}
}
handler.save = (self) => {
	let buf1 = {targets: self.namespace.targets, webshells: self.namespace.webshells, flags: self.namespace.flags};
		fs.writeFileSync('./awd.json', JSON.stringify(buf1, null, 4));
}
handler.load = (self) => {
	let buf2 = JSON.parse(fs.readFileSync('./awd.json').toString());
	self.namespace.targets = buf2.targets;
	self.namespace.webshells = buf2.webshells;
	self.namespace.flags = buf2.flags;
}
handler.clear = (self) => {
	self.namespace.targets = [];
	self.namespace.webshells = [];
	self.namespace.flags = [];
}
handler.info = (self) => {
	console.log('token'.cyan.bold, self.namespace.token);
	console.log('get flag url'.cyan.bold, self.namespace.getflagurl);
	console.log('submit flag url'.cyan.bold, self.namespace.submitflagurl);
	console.log('exec string'.cyan.bold, self.namespace.exec_str);
	console.log('eval string'.cyan.bold, self.namespace.eval_str);
	console.log('timeout'.cyan.bold, self.namespace.timeout);
	console.log('shellname'.cyan.bold, self.namespace.shellname);
	console.log('saveflag'.cyan.bold, self.namespace.saveflag);
}
handler.saveinfo = (self) => {
	fs.writeFileSync('./config.json', JSON.stringify({
		getflagurl: self.namespace.getflagurl,
		submitflagurl: self.namespace.submitflagurl,
		token: self.namespace.token,
		exec_str: self.namespace.exec_str,
		eval_str: self.namespace.eval_str,
		timeout: self.namespace.timeout,
		shellname: self.namespace.shellname
	}, null, 4));
}

module.exports = handler;